import React,{ Component } from 'react';
import './uploadPic.scss';
import '../index/index.scss';
import { upLoadImg, getUserList, editImgList } from '@/api/user';

export default class UploadPic extends Component{
	constructor (props) {
		super(props)
		this.state = {
			imgList: []
		}
	}
	goBack () { //返回上一级
		this.props.history.goBack()
	}
	componentWillMount() {
		document.title = '上传照片';
		getUserList().then(res => {
			this.setState({
				imgList: res.data
			})
		})
	}
	deleteImg (id) {
		let ids = []
		this.state.imgList.forEach((item, index) => {
			if (item.img_id !== id) {
				ids.push(item.img_id)
			}
		})
		editImgList({img_id: ids}).then(res => {
			if (res.code === 1) {
				getUserList().then(res => {
					this.setState({
						imgList: res.data
					})
				})
			}
		})
	}
	addImg (e) {
		// let that = this
		const $img = e.target.files[0]
		let formData = new FormData()
    formData.append('file', $img)
		upLoadImg(formData).then(res => {
			if (res.code === 1) {
				this.setState({
					imgList: [...this.state.imgList, {
						img_url: res.data.url,
						img_id: res.data.img_id
					}]
				}, () => {
					let ids = []
					this.state.imgList.forEach((item, index) => {
						ids.push(item.img_id)
					})
					editImgList({img_id: ids}).then(res => {
					})
				})
			}
		})
	}
	render(){
		return(
			<div className="uploadPic">
				{/*<div className="title">
					<div onClick={this.goBack.bind(this)}><i className="glyphicon glyphicon-left"></i></div>
					<div>上传照片</div>
					<div></div>
				</div>*/}
				<div className="uploadPic_content">
					{
						this.state.imgList.map((item, index) => {
							return (
								<div className="img-show" key={index}>
									<i className="glyphicon glyphicon-del" onClick={this.deleteImg.bind(this, item.img_id)}></i>
									<img src={item.img_url} alt='11'/>
								</div>
							)
						})
					}
					{
						this.state.imgList.length < 4 ?
						<div className="add_uploadPic img-show">
							<input type="file" onChange={this.addImg.bind(this)}  />
							<i className="glyphicon glyphicon-add"></i>
						</div> : ''
					}
					
				</div>
			</div>
		)
	}
}
